package top.andnux.weather.fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewbinding.ViewBinding;

import top.andnux.weather.view.BaseView;

public abstract class BaseFragment<T extends ViewBinding> extends Fragment implements BaseView {

    protected T binding;
    private ProgressDialog waitingDialog;
    protected Activity context;

    protected abstract T createViewBinding(LayoutInflater inflater);

    protected abstract void onCreated(@Nullable Bundle savedInstanceState);

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = createViewBinding(inflater);
        context = requireActivity();
        onCreated(savedInstanceState);
        return binding.getRoot();
    }

    @Override
    public void showLoading(String content) {
        if (waitingDialog != null) {
            waitingDialog.dismiss();
            waitingDialog = null;
        }
        waitingDialog = new ProgressDialog(requireContext());
        waitingDialog.setTitle("温馨提示");
        waitingDialog.setMessage(content);
        waitingDialog.setIndeterminate(true);
        waitingDialog.setCancelable(false);
        waitingDialog.show();
    }

    @Override
    public void hideLoading() {
        if (waitingDialog != null) {
            waitingDialog.dismiss();
            waitingDialog = null;
        }
    }

    @Override
    public void onDestroy() {
        if (binding != null) {
            binding = null;
        }
        super.onDestroy();
    }

    @Override
    public void toast(String msg) {
        Toast.makeText(requireContext(), msg, Toast.LENGTH_SHORT).show();
    }
}
